﻿using System.Configuration;
using System.Globalization;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using Microsoft.Practices.Unity.InterceptionExtension;

namespace SGRapidForm.Common
{
    public static class ServiceLoader
    {
        private static readonly TransparentProxyInterceptor injector = new TransparentProxyInterceptor();
        
        public static IUnityContainer Container
        { get; private set; }

        static ServiceLoader()
        {
            UnityConfigurationSection unitySection = ConfigurationManager.GetSection("unity") as UnityConfigurationSection;
            if (unitySection == null)
            {
                throw new ConfigurationErrorsException(string.Format(CultureInfo.CurrentCulture, "Missing Unity configuration section."));
            }

            Container = new UnityContainer();
            UnityContainerElement containerElement;
            containerElement = unitySection.Containers.Default;
            containerElement.Configure(Container);
            Container.AddNewExtension<Interception>();
        }

        public static T LoadService<T>()
        {
            Container.Configure<Interception>().SetDefaultInterceptorFor(typeof(T), injector);
            return Container.Resolve<T>();
        }

        public static T LoadService<T>(string serviceName)
        {
            Container.Configure<Interception>().SetDefaultInterceptorFor(typeof(T), injector);
            return Container.Resolve<T>(serviceName);
        }
    }
}